<?php

namespace App\Models;

use App\Models\BaseModel;

/**
 * 管理员角色关联模型
 */
class AdminRole extends BaseModel
{
    protected $table = 'admin_roles';

    /**
     * 获取表字段
     * @return array
     */
    protected function columns(): array
    {
        return [
            'id',
            'admin_id',
            'role_id',
            'created_at',
            'updated_at',
            'deleted_at'
        ];
    }

    /**
     * 关联管理员
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function admin()
    {
        return $this->belongsTo(Admins::class, 'admin_id', 'id');
    }

    /**
     * 关联角色
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function role()
    {
        return $this->belongsTo(Role::class, 'role_id', 'id');
    }

    /**
     * 构建查询条件
     * @param array $params
     * @return \Illuminate\Database\Eloquent\Builder
     */
    protected function buildQuery(array $params = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = parent::buildQuery($params);

        if (!empty($params['role_ids'])) {
            $query->whereIn('role_id', $params['role_ids']);
        }
        return $query;
    }

    /**
     * 获取管理员的角色信息
     * @param int $adminId 管理员ID
     * @return array
     */
    public function getAdminRoles(int $adminId): array
    {
        return $this->select('roles.id', 'roles.name')
            ->join('roles', 'admin_roles.role_id', '=', 'roles.id')
            ->where('admin_roles.admin_id', $adminId)
            ->where('roles.status', Role::STATUS_ENABLED)
            ->get()
            ->toArray();
    }
}
